package com.redistest.seckill.controller;

import com.redistest.seckill.service.IGoodsService;
import com.redistest.seckill.vo.GoodsVo;
import com.redistest.seckill.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2025-04-11
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private IGoodsService goodsService;

    @GetMapping("/toList")
    public Result toList(){
        List<GoodsVo> goodsList=goodsService.findGoodsVo();
        return Result.success(goodsList,"秒杀商品查询成功");
    }

    @GetMapping("/goodsDetail/{id}")
    public Result goodsDetail(@PathVariable Long id){
        GoodsVo goodsVo=goodsService.goodsDetail(id);
        return Result.success(goodsVo,"商品详情查询成功");
    }

    @PutMapping("/doSeckill")
    public Result doSeckill(
            @RequestParam Long goodsId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime
    ) {
        // 1. 参数校验
        if (goodsId == null || startTime == null || endTime == null) {
            return Result.error(400, null, "参数不能为空");
        }
        if (endTime.before(startTime)) {
            return Result.error(400, null, "结束时间必须晚于开始时间");
        }

        // 2. 查询商品是否存在
        GoodsVo goods = goodsService.goodsDetail(goodsId);
        if (goods == null) {
            return Result.error(404, null, "商品不存在");
        }

        // 3. 更新秒杀时间
        goods.setStartDate(startTime);
        goods.setEndDate(endTime);
        boolean updated = goodsService.updateGoodsVo(goods);
        if (!updated) {
            return Result.error(500, null, "更新秒杀时间失败");
        }

        return Result.success(null,"秒杀时间设置成功");
    }
}
